<template>
    <el-dialog :model-value="props.modelValue" @update:model-value="emit('update:modelValue', $event)" title="选择商品"
        width="990">
        <!-- 整体容器：使用 flex 横向布局 -->
        <div class="goods-layout">
            <!-- 使用 el-container 构建主布局 -->
            <el-container>
                <el-header style="padding: 0; border-bottom: 1px solid #e8e8e8;">
                    <div class="header-toolbar">
                        <el-form :model="searchForm" label-width="auto" class="search-form" inline>

                            <el-form-item>
                                <el-input v-model="searchForm.keyword" placeholder="商品名称/商品编号/供应商名称查询" />
                            </el-form-item>

                            <el-form-item label="仓库" style="width: 200px">
                                <el-select v-model="searchForm.warehouse" placeholder="(空)" clearable
                                    style="width: 100%">
                                    <el-option v-for="item in warehouseData" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-button type="primary" @click="searchGoods">查询</el-button>
                        </el-form>
                    </div>
                </el-header>
                <!-- 主内容区（含 header + 表格 + 分页） -->
                <el-container class="main-container">

                    <!-- 内容主体：分类提示栏 + 表格 + 分页 -->
                    <el-main class="table-main">
                        <!-- 分类提示栏 -->
                        <div class="category-bar">
                            <el-icon class="toggle-icon" @click="toggleAside">
                                <DArrowRight v-if="!asideCollapsed" />
                                <DArrowLeft v-else />
                            </el-icon>
                        </div>

                        <div class="table-wrapper">
                            <el-table :data="goodsList" style="width: 100%" height="100%" v-loading="tableLoad" border
                                @selection-change="handleSelectionChange">
                                <el-table-column type="selection" width="55px" />

                                <el-table-column prop="code" label="商品编号" width="180" />
                                <el-table-column prop="picture" label="图片" width="180">
                                    <template #default="scope">
                                        <el-image style="width: 50px; height: 50px" :src="imgStr + scope.row.picture"
                                            preview-teleported :preview-src-list="[imgStr + scope.row.picture]"
                                            fit="cover" />
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="商品名称" width="180" />
                                <el-table-column prop="typeName" label="商品类别" width="180" />
                                <el-table-column prop="specification" label="规格型号" width="180" />
                                <el-table-column prop="defaultSupplierInfo" label="默认供应商" width="180" />
                                <el-table-column prop="brandName" label="品牌" width="180" />
                                <el-table-column label="单位" width="180">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.selectedUnitId" placeholder="" style="width: 100%"
                                            @change="(val) => handleUnitChange(scope.row, val)"
                                            :disabled="scope.row.unitType == null">
                                            <el-option v-for="unit in unitOptionsMap[scope.row.id] || []" :key="unit.id"
                                                :label="unit.name" :value="unit.id" />
                                        </el-select>
                                    </template>

                                </el-table-column>
                                <el-table-column prop="warehouseName" label="当前仓库" width="180" />
                                <el-table-column prop="stock" label="当前库存" width="180" />
                                <el-table-column prop="initQuantity" label="期初数量" width="180" />
                                <el-table-column prop="cost" label="单价成本" width="180" />
                                <el-table-column prop="initPrice" label="期初总价" width="180" />
                                <el-table-column prop="predictPrice" label="预计采购价" width="180" />
                                <el-table-column prop="purchasePrice" label="最高采购价" width="180" />
                                <el-table-column prop="salePrice" label="最低销售价" width="180" />
                                <el-table-column prop="retailPrice" label="零售价" width="180" />
                                <el-table-column prop="wholesalePrice" label="批发价" width="180" />
                                <el-table-column prop="vipPrice" label="VIP会员价" width="180" />
                                <el-table-column prop="taxRate" label="商品税率" width="180" />
                                <el-table-column prop="discountRate" label="折扣率" width="180" />
                                <el-table-column prop="defaultPrice" label="默认价格" width="180" />
                                <el-table-column prop="createDate" label="创建时间" width="180" />
                                <el-table-column prop="remark" label="备注" width="180" />
                            </el-table>
                        </div>

                        <!-- 分页 -->
                        <div class="pagination-container">
                            <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
                                :page-sizes="[5, 10, 15, 20]" :background="true"
                                layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                        </div>
                    </el-main>
                    <!-- 侧边分类树（可折叠） -->
                    <el-aside v-show="!asideCollapsed" width="250px" class="goods-aside">
                        <el-card>
                            <template #header>
                                <el-input v-model="typeFilter" placeholder="请输入类别名称" suffix-icon="Search" clearable />
                            </template>
                            <el-tree ref="treeRef" :data="treeSelectData"
                                :props="{ value: 'id', label: 'name', children: 'children' }" default-expand-all
                                node-key="id" @node-click="handleNodeClick" :filter-node-method="filterTreeNode">
                                <template #default="{ data }">
                                    <span>
                                        <el-icon>
                                            <Folder v-if="data.children && data.children.length > 0" />
                                            <Document v-else />
                                        </el-icon>
                                        {{ data.name }}
                                    </span>
                                </template>
                            </el-tree>
                        </el-card>
                    </el-aside>
                </el-container>
            </el-container>
        </div>
        <div class="dialog-footer">
            <el-button type="primary" @click="AddGoods">新增商品</el-button>
            <div class="right-buttons">
                <el-button @click="emit('update:modelValue', false)">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确定</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, defineProps, defineEmits, inject, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'
// import axios from 'axios'
import { useRouter } from 'vue-router';
import imgStr from '@/store/imgStr';
let axios = inject("axios")
const router = useRouter();

// ========== Props & Emits ==========
const props = defineProps({
    modelValue: Boolean
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const tableLoad = ref(false)
const asideCollapsed = ref(false)
const typeFilter = ref('')
const treeRef = ref()

const searchForm = reactive({
    keyword: '',
    status: 1,
    warehouse: null,
    type: null // 类别ID
})

const pageInfo = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

const selectedProducts = ref([])

// 不同单位类型：不同单位列表
const unitOptionsMap = ref({})
defineExpose({ "unitOptionsMap": unitOptionsMap })

// 获取单位列表
const getUnitList = async (goods, unitType) => {
    const { id, unit, unitName } = goods

    // 已缓存？直接返回
    if (unitOptionsMap.value[id]) {
        return unitOptionsMap.value[id]
    }

    let unitList = []

    if (unitType === 0) {
        unitList = [{
            id: unit,
            name: unitName,
            conversion: 1
        }]
    } else if (unitType === 1) {
        // 多单位：调接口（注意：是否需要传 goodsId？看后端）
        try {
            const res = await axios.get('/api/basic/goods/allUnitsDetailsByUnitsId', { params: { unitsId: unit } })
            if (res.data.code === 5200) {
                unitList = (res.data.unitsDetailList || []).map(u => ({
                    id: u.id,
                    name: u.name,
                    conversion: u.conversion,
                    unitsId: unit
                }))
            } else {
                ElMessage.warning('单位加载失败')
                unitList = []
            }
        } catch (err) {
            console.error('加载单位出错:', err)
            ElMessage.error('单位加载异常')
            unitList = []
        }
    }

    // 存入缓存：key = 商品ID
    unitOptionsMap.value[id] = unitList
    return unitList
}

// ========== 商品列表 ==========
const goodsList = ref([])
// 获取商品分页
const getGoodsList = async () => {
    tableLoad.value = true

    try {
        const res = await axios.get('/api/basic/goods/goodsByPage', {
            params: {
                pageNum: pageInfo.pageNum,
                pageSize: pageInfo.pageSize,
                ...searchForm
            }
        })


        if (res.data.code === 5200) {
            goodsList.value = res.data.pageInfo.list
            pageInfo.total = res.data.pageInfo.total
            pageInfo.pageNum = res.data.pageInfo.pageNum

            console.log(warehouseData.value)
            goodsList.value.forEach(item => {
                if (searchForm.warehouse) {
                    console.log("searchForm.warehouse", searchForm.warehouse)
                    item.warehouseName = warehouseData.value.find(item => item.id == searchForm.warehouse).name
                    item.warehouse = searchForm.warehouse
                }
                else {
                    item.warehouseName = '';
                    item.warehouse = '';
                }
                if ([0, 1].includes(item.unitType)) {
                    getUnitList(item, item.unitType).then(units => {
                        if (item.unitType == 0) {
                            item.selectedUnitId = item.unit
                        } else if (item.unitType == 1) {
                            const baseUnit = units.find(u => u.conversion === 1);
                            // 如果找不到 conversion=1 的，就选第一个（兜底）
                            item.selectedUnitId = baseUnit ? baseUnit.id : (units[0]?.id || item.unit);
                        }
                    })
                }

            })


        } else {
            ElMessage.error(res.data.msg)
        }
    } catch {
        ElMessage.error('获取商品分页出错')
    } finally {
        tableLoad.value = false
    }
}

const handleUnitChange = (row, newUnitId) => {
    const units = unitOptionsMap.value[row.id] || []
    const selected = units.find(u => u.id === newUnitId)

    if (selected) {
        // 只更新 selectedUnitId，不污染 row.unit
        row.selectedUnitId = selected.id
        row.selectedUnitName = selected.name
    }
}

// ========== 商品分类树 ==========
const goodsType = ref([])
const getGoodsType = async () => {

    try {
        const res = await axios.get('/api/basic/goods/allGoodsType')

        if (res.data.code === 5200) {
            goodsType.value = res.data.goodsTypeList
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

const treeData = computed(() => {
    const roots = []
    const map = {}
    goodsType.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    goodsType.value.forEach(item => {
        if (item.parentId === null || item.parentId === '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// ====== 仓库 ======
const warehouseData = ref([])

const getWarehouseData = async () => {
    try {
        const res = await axios.get('/api/basic/warehouse/allWarehouses')

        if (res.data.code === 5200) {
            warehouseData.value = res.data.warehouseList
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 切换侧边栏
const toggleAside = () => {
    asideCollapsed.value = !asideCollapsed.value
}

const searchGoods = () => {
    pageInfo.pageNum = 1
    getGoodsList()
}

const handleNodeClick = (data) => {
    searchForm.type = data.id === '0' ? null : data.id
    pageInfo.pageNum = 1
    getGoodsList()
}

const handleSelectionChange = (selection) => {
    selectedProducts.value = selection
}

const handleConfirm = () => {
    // if (selectedProducts.value.length === 0) {
    //     ElMessage.warning('请选择至少一个商品')
    //     return
    // }
    // 创建副本，避免污染原数据（虽然弹窗要关了，但好习惯）
    const result = selectedProducts.value.map(item => {
        return {
            ...item,
            // 把 unit 替换为实际选中的单位ID（单单位或多单位都适用）
            unit: item.selectedUnitId,
            // 可选：补充 unitName（如果父组件需要）
            unitName: unitOptionsMap.value[item.id]?.find(u => u.id === item.selectedUnitId)?.name || item.unitName,
            unitList: unitOptionsMap.value[item.id]
        }
    })

    emit('confirm', result)
    closeDialog()
}

const closeDialog = () => {
    emit('update:modelValue', false)
}

// 分页
const handleSizeChange = (size) => {
    pageInfo.pageSize = size
    pageInfo.pageNum = 1
    getGoodsList()
}
const handleCurrentChange = (page) => {
    pageInfo.pageNum = page
    getGoodsList()
}

// 树过滤
watch(typeFilter, (val) => {
    treeRef.value?.filter(val)
})
const filterTreeNode = (value, data) => {
    if (!value) return true
    return data.name.includes(value)
}

// 新增商品跳转方法
const AddGoods = () => {
    closeDialog()
    router.push({ name: 'AddGoodsCompoent' });
};

// ========== 生命周期 ==========
onMounted(async () => {
    await getWarehouseData()
    await getGoodsType()
    await getGoodsList()
})
</script>

<style scoped>
.goods-layout {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
}

/* 主容器：header + main */
.el-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.main-container {
    flex: 1;
    display: flex;
    flex-direction: row;
    gap: 16px;
    margin-top: 16px;
    overflow: hidden;
}

.header-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
}

.search-form {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-form .el-input,
.search-form .el-select {
    width: auto;
}

.table-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-width: 0;
    /* 防止 flex 子项溢出 */
}

.category-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    background-color: #eeeeee;
    padding: 0 16px;
    font-size: 14px;
}

.toggle-icon {
    cursor: pointer;
    font-size: 18px;
    color: #606266;
}

.table-wrapper {
    flex: 1;
    overflow: auto;
    margin-top: 8px;
    border: 1px solid #e8e8e8;
    /* 关键：限制最大高度，避免撑开弹窗 */
    max-height: 500px;
    /* 可根据需求调整 */
}

/* 表头固定：需配合 el-table 的 height 属性，但此处我们用 CSS 模拟更可靠 */
:deep(.el-table__header) {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: #f5f7fa;
}

:deep(.el-table th) {
    background-color: #f5f7fa !important;
}

.goods-aside {
    flex-shrink: 0;
    width: 250px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.goods-aside :deep(.el-card) {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.goods-aside :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: auto;
}

.goods-aside :deep(.el-tree) {
    flex: 1;
    overflow: auto;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
}

.dialog-footer .right-buttons {
    display: flex;
    gap: 8px;
}
</style>